package com.example.myapplication.view;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import com.example.myapplication.R;
import com.example.myapplication.dao.FieldNotebookDao;
import com.example.myapplication.dao.MySQLConnection;
import com.example.myapplication.localdatabase.AppDatabase;
import com.example.myapplication.util.FieldNotebookAdapter;
import com.example.myapplication.model.FieldNotebookEntity;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test3 extends AppCompatActivity {
    private AppDatabase appDatabaseconnection;
    private FieldNotebookDao dao;
    private ExecutorService executor;
    private MySQLConnection mySQLConnection;// 如果需要添加笔记本的按钮
    private FieldNotebookAdapter adapter;
    CheckBox cbSelectAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.test_3); // 加载 activity_test3.xml

        mySQLConnection = new MySQLConnection();

        // 初始化数据库
        appDatabaseconnection= Room.databaseBuilder(//不存储数据、不处理交互逻辑，只渲染 Adapter 提供的视图
                getApplicationContext(),
                AppDatabase.class,
                "field_notebook_db"
        ).fallbackToDestructiveMigration().build(); // 测试阶段使用
        dao = appDatabaseconnection.fieldNotebookDao();
        executor = Executors.newSingleThreadExecutor();

        // 初始化 RecyclerView
        RecyclerView rvFieldNotebooks = findViewById(R.id.rv_field_notebooks);
        rvFieldNotebooks.setLayoutManager(new LinearLayoutManager(this));

        // 查询所有记录并设置 Adapter


        cbSelectAll = findViewById(R.id.cb_select_all);//全选
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (adapter != null) {
                adapter.setAllChecked(isChecked); // 设置全选/全不选。。调用的竟然是
            }
        });

        Button btnSync = findViewById(R.id.btn_sync);
        btnSync.setOnClickListener(v -> syncToCloud());

        loadAllRecords();
    }




    private void syncToCloud() {
        if (adapter == null) {
            Toast.makeText(this, "没有记录可同步", Toast.LENGTH_SHORT).show();
            return;
        }
        List<FieldNotebookEntity> selectedRecords = adapter.getSelectedRecords();
        if (selectedRecords.isEmpty()) {
            Toast.makeText(this, "请至少选择一条记录", Toast.LENGTH_SHORT).show();
            return;
        }
        executor.execute(() -> {
            if (!mySQLConnection.isConnected()) {
                mySQLConnection.connect();
                if (!mySQLConnection.isConnected()) {
                    runOnUiThread(() -> Toast.makeText(this, "数据库连接失败", Toast.LENGTH_SHORT).show());
                    return;
                }
            }
            boolean hasConflict = false;
            boolean anySuccess = false;
            for (FieldNotebookEntity record : selectedRecords) {
                if (mySQLConnection.isNameExists(record.name)) {
                    hasConflict = true;
                    Log.d("Test3", "冲突: " + record.name);
                    continue;
                }
                boolean success = mySQLConnection.insert(
                        record.pointId, record.name, record.recordTime, record.longitude,
                        record.latitude, record.outcrop, record.pointMeaning, record.description, record.photo
                );
                if (success) {
                    anySuccess = true;
                    record.isuploaded = 1;
                    dao.update(record);
                    Log.d("Test3", "上传成功: " + record.name);
                } else {
                    Log.e("Test3", "上传失败: " + record.name);
                }
            }
            List<FieldNotebookEntity> updatedList = dao.getUnuploadedRecords();
            boolean finalHasConflict = hasConflict;
            boolean finalAnySuccess = anySuccess;
            runOnUiThread(() -> {
                adapter.updateData(updatedList);
                if (finalHasConflict) {
                    Toast.makeText(this, "存在冲突，前往修改", Toast.LENGTH_LONG).show();
                } else if (finalAnySuccess) {
                    Toast.makeText(this, "同步完成", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "同步失败，请检查数据或数据库", Toast.LENGTH_SHORT).show();
                }
            });
        });
    }
    private void loadAllRecords() {
        executor.execute(() -> {
            List<FieldNotebookEntity> dataList = dao.getAllFieldNotebooks();
            runOnUiThread(() -> {
                adapter = new FieldNotebookAdapter(this, dataList);
                RecyclerView rvFieldNotebooks = findViewById(R.id.rv_field_notebooks);
                rvFieldNotebooks.setAdapter(adapter);
            });
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!executor.isShutdown()) {
            executor.shutdown();
        }
    }
}